﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ChatForum.Client
{
    public partial class ChatWindow : System.Web.UI.Page
    {
        [System.Web.Services.WebMethod]
        public static object OnRefresh(string targetUser)
        {
            if (HttpContext.Current.Application["ChatData"] != null)
            {
                List<PingData> allPingData = (List<PingData>)HttpContext.Current.Application["ChatData"];

                var pingToMeFromTarget = allPingData.Where(pd => pd.SourceUser == targetUser && pd.TargetUser == HttpContext.Current.User.Identity.Name);
                var pingFromMetoTarget = allPingData.Where(pd => pd.SourceUser == HttpContext.Current.User.Identity.Name && pd.TargetUser == targetUser);

                var output = from pd in pingFromMetoTarget.Concat(pingToMeFromTarget).OrderBy(pd => pd.PingTime)
                             select new
                             {
                                 Sender = pd.SourceUser,
                                 Text = pd.PingText
                             };

                //foreach (var item in pingToMeFromTarget)
                //{
                //    allPingData.RemoveAll(pd => pd.SourceUser == item.SourceUser
                //        && pd.TargetUser == item.TargetUser
                //        && pd.PingText == item.PingText
                //        && pd.PingTime == item.PingTime);
                //}

                //foreach (var item in pingFromMetoTarget)
                //{
                //    allPingData.RemoveAll(pd => pd.SourceUser == item.SourceUser
                //        && pd.TargetUser == item.TargetUser
                //        && pd.PingText == item.PingText
                //        && pd.PingTime == item.PingTime);
                //}

                return output.ToArray();
            }
            return null;
        }

        [System.Web.Services.WebMethod]
        public static void OnPing(string targetUser, string pingText)
        {
            if (HttpContext.Current.Application["ChatData"] == null)
                HttpContext.Current.Application["ChatData"] = new List<PingData>();
            {
                List<PingData> allPingData = (List<PingData>)HttpContext.Current.Application["ChatData"];
                if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
                {
                    allPingData.Add(new PingData(HttpContext.Current.User.Identity.Name, targetUser, pingText));
                }
            }
        }
    }
}